<?php
/**
 * Created by gumaor.com
 * User: tommy
 */

namespace business\album;


use model\album\AlbumModel;
use Timo\Core\Application;
use Timo\Core\Request;
use Timo\Core\Response;
use Timo\Loader;

class AlbumSaver
{
    private $id;

    protected $data;

    /**
     * @var AlbumModel
     */
    protected $model;

    public function __construct()
    {
        $this->receiveData();
        $this->checkForm();
        $this->model = Loader::model(AlbumModel::class);
    }

    /**
     * 入口
     *
     * @return array
     */
    public function run()
    {
        if ($this->id == 0) {
            return $this->publish();
        }
        return $this->update();
    }

    /**
     * 发布专辑
     *
     * @return array
     */
    public function publish()
    {
        $this->data['created'] = NOW_TIME;
        $this->data['updated'] = NOW_TIME;
        $ret = $this->model->insert($this->data);
        if (!$ret) {
            return [1, '发布失败，请稍后重试'];
        }
        return [0, '发布成功'];
    }

    /**
     * 更新专辑
     *
     * @return array
     */
    public function update()
    {
        $this->data['updated'] = NOW_TIME;
        $ret = $this->model->where($this->id)->update($this->data);
        if (!$ret) {
            return [1, '更新失败，请稍后重试'];
        }
        return [0, '更新成功'];
    }

    /**
     * 接收数据
     */
    private function receiveData()
    {
        $this->id = Request::post('id', 0, 'intval');
        $this->data['uid'] = Request::post('uid', 0, 'intval');
        $this->data['title'] = Request::post('title', '', 'strip_tags');
        $this->data['cover'] = Request::post('cover', '', 'strip_tags');
        $this->data['status'] = Request::post('status', 1, 'intval');
    }

    /**
     * 表单检测
     */
    private function checkForm()
    {
        $msg = '';
        if ($this->id < 0 || $this->data['uid'] <= 0) {
            $msg = 'params error';
        } elseif (empty($this->data['title'])) {
            $msg = '请填写标题';
        } elseif (empty($this->data['cover'])) {
            $msg = '请上传封面';
        }

        if (!empty($msg)) {
            Response::send(Application::result(1, $msg));
        }
    }
}
